import { z } from "zod";
import axios from 'axios'
import { RequestHandler } from "express";
import { SsoToken, SsoUser, useEntityManager } from "./entities";
import jwt from "jsonwebtoken";
import { useSecret } from "./utils";
import dayjs from "dayjs";

const handler: RequestHandler = async (req, res, next) => {
    const input = z.object({
        access_token: z.string(),
    })
    const body = input.parse(req.query)
    return await useEntityManager(async m => {
        const token = await m.findOne(SsoToken, {
            where: { access_token: body.access_token }
        })
        if (!token) {
            res.json({ message: `toeken not found`, success: false })
            return;
        }
        if (Date.now() > token.expires_in) {
            res.json({ message: `toeken expired`, success: false })
            return;
        }
        const authHost = process.env.AUTH_HOST
        const url = `${authHost}/current/user`
        const result = await axios.get(url, {
            headers: {
                Authorization: 'Bearer ' + body.access_token
            }
        }).then(res => res.data)
        if (result.code === 200) {
            const user = result.data;
            const newUser = m.create(SsoUser, {
                ...user,
                openid: token.openid,
            })
            await m.save(newUser)
            return res.json({ success: true, message: 'ok', data: { token: token.access_token, expire: token.expires_in } })
        }
        return res.json({ success: false, message: result.message })
    });
}
export default handler;